<template>
  <div class="homeContainer">
    <h1>职工信息登记系统</h1>
    <el-row type="flex" align="middle" justify="space-evenly" style="margin-left: -40px;">
      <el-col :span="16">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="编号:" prop="id">
            <el-input v-model.number="form.id" class="input" ref="idInput" data-ref="idInput"
                      @keydown="focusNextInput"></el-input>
          </el-form-item>
          <el-form-item label="姓名:" prop="name">
            <el-input v-model.trim="form.name" class="input" ref="nameInput" data-ref="nameInput"
                      @keydown="focusNextInput"></el-input>
          </el-form-item>
          <el-form-item label="工资:" prop="salary">
            <!--            <el-input v-model.number="form.salary" class="input" ref="salaryInput" data-ref="salaryInput"-->
            <!--                      @keydown="focusNextInput"></el-input>-->
            <el-input-number style="width: 350px;"
                             :min="1.00" :max="30000.00"
                             v-model="form.salary"
                             class="input" ref="salaryInput"
                             data-ref="salaryInput"
                             :precision="2" :step="0.01"

                             @keydown="focusNextInput"></el-input-number>
          </el-form-item>
          <el-form-item label="住址:" prop="address">
            <el-input v-model.trim="form.address" class="input" ref="addressInput" data-ref="addressInput"
                      @keydown="focusNextInput"></el-input>
          </el-form-item>
          <el-form-item class="button-group">
            <el-button type="primary" @click="submitForm('form')">确认</el-button>
            <el-button @click="resetForm('form')">取消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!-- add the toggle button here -->
    <el-button
        class="flex items-center justify-between w-16 h-8 px-1 rounded-full bg-gray-300 dark:bg-gray-800"
        @click="toggleTheme"
        style="
        position: absolute;
        top: 20px;
        right: 20px;">
      <span
          class="w-6 h-6 rounded-full bg-yellow-500 dark:bg-gray-300 transform transition-transform duration-300"
          :class="{ 'translate-x-8': isDark }"
      ></span>
      <span v-if="isDark" class="text-xl text-gray-300">☀️</span>
      <span v-else class="text-xl text-yellow-500">🌙</span>
    </el-button>
    <About class="guanyuabout"/>
  </div>
</template>

<script>
// import { useDark } from "@vueuse/core";
import {invoke} from "@tauri-apps/api/tauri";
import {useDark, useToggle} from '@vueuse/core'
import About from '../components/About.vue'

export default {
  name: "App",
  components: {
    About
  },
  setup() {
    // const { isDark, toggleDark } = useDark();
    const isDark = useDark()
    const toggleDark = useToggle(isDark)
    // a wrapper function to toggle dark mode and set theme for Tauri window
    const toggleTheme = () => {
      // console.log('isdark:',isDark.value)
      // toggle dark mode state
      toggleDark();
      // set theme for Tauri window
      invoke("set_theme", {
        theme: isDark ? "Dark" : "Light",
      });


    };

    return {toggleDark, toggleTheme, isDark};
  },
  data() {
    return {
      form: {
        id: "",
        name: "",
        salary: 1.00,
        address: "",

      },
      rules: {
        id: [
          {required: true, message: "编号不能为空", trigger: "blur"},
          {type: "number", message: "编号必须是数字", trigger: "blur"},
          {
            min: 1,
            max: 5000,
            type: "number",
            message: "编号必须是1到5000之间的整数",
            trigger: "blur",
          },
          // TODO: add a validator to check if id is unique
        ],
        name: [
          {required: true, message: "姓名不能为空", trigger: "blur"},
          {min: 3, max: 10, message: "姓名必须是3到10个字符", trigger: "blur"},
        ],
        salary: [
          {type: "number", message: "工资必须是数字", trigger: "blur"},
          {
            min: 1.0,
            max: 30000.0,
            type: "number",
            message: "工资必须是1.00到30000.00之间的小数（或整数）",
            trigger: "blur",
          },
          // TODO: add a validator to check if salary has at most two decimal places
        ],
        address: [{max: 30, message: "住址最多30个字符", trigger: "blur"}],
      },
      inputRefs: ["idInput", "nameInput", "salaryInput", "addressInput"],
    };
  },
  methods: {

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$message.success({
            message: "登记成功",
            type: "success",
          });
          this.resetForm('form');
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // focusNextInput(e) {
    //   if (e.key === "Enter") {
    //     // get the current input element
    //     const currentInput = e.target;
    //     // get the current input element's ref value
    //     const currentRef = currentInput.getAttribute("data-ref");
    //     // get the index of the current input element in the inputRefs array
    //     const currentIndex = this.inputRefs.indexOf(currentRef);
    //     // get the index of the next input element
    //     const nextIndex = currentIndex + 1;
    //     // check if the next index is valid
    //     if (nextIndex < this.inputRefs.length) {
    //       // get the next input element's ref value
    //       const nextRef = this.inputRefs[nextIndex];
    //       // get the next input element using $refs object
    //       const nextInput = this.$refs[nextRef];
    //       // console.log('tset', nextRef)
    //       // focus on the next input element
    //       nextInput.focus();
    //     }
    //   }
    // },
    focusNextInput(e) {
      if (e.key === "Enter") {
        // get the current input element
        const currentInput = e.target;
        // get the current input element's ref value
        let currentRef = currentInput.getAttribute("data-ref");
        // get the index of the current input element in the inputRefs array
        if(currentRef==null){
          currentRef="salaryInput";
        }
        const currentIndex = this.inputRefs.indexOf(currentRef);

        // get the index of the next input element
        const nextIndex = currentIndex + 1;
        // check if the next index is valid
        // console.log('suoyin:',currentRef)
        if (nextIndex < this.inputRefs.length) {
          // get the next input element's ref value
          const nextRef = this.inputRefs[nextIndex];
          // console.log('tets',nextRef)
          // get the next input element using $refs object
          const nextInput = this.$refs[nextRef];
          // focus on the next input element
          nextInput.focus();
        }
      }
    }

  },
};
</script>

<style>
.guanyuabout {
  position: absolute;
  top: 20px;
  right: 80px;
}

.homeContainer {
  width: 600px;
//margin-top: 100px; animation-name: fadeIn;
  animation-duration: 2s;
  margin: 10% auto;
}

h1 {
  text-align: center;
  width: 300px;
  margin-left: auto;
  margin-right: auto;
}

.input {
  height: 40px;
}

.button-group {
  display: flex;
}

.button-group button {
  flex-grow: 1;
}

.button-group button + button {
  margin-left: 20px;
}

/* add some animations and transitions */


@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* scale up the input on focus */
.input:focus-within {
  transform-origin: center;
  transform: scale(1.05);

  /* add a transition for scaling */
  transition-property: transform;
  transition-duration: .5s;
}

/* rotate the button on hover */
.button-group button:hover {
  transform-origin: center;
  transform: rotate(10deg);

  /* add a transition for rotating */
  transition-property: transform;
  transition-duration: .5s;
}

/* add a loading spinner to the button on click */
.button-group button:active {
  position: relative;
}

.button-group button:active::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 20px;
  height: 20px;
  margin-top: -10px;
  margin-left: -10px;
  border-radius: 50%;
  border: 2px solid white;
  border-top-color: transparent;
  animation-name: spin;
  animation-duration: 100000s;
  animation-iteration-count: infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* add dark mode styles */

html,
body {
  padding: 0;
  margin: 0;
}

/* Define styles for the default root window element */
:root {
  --background-color-primary: #ebebeb;
  --background-color-secondary: #fafafa;
  --accent-color: #cacaca;
  --text-primary-color: #222;
  --element-size: 4rem;
}

/* Define styles for the root window with dark - mode preference */
:root.dark-theme {
  --background-color-primary: #1e1e1e;
  --background-color-secondary: #2d2d30;
  --accent-color: #3f3f3f;
  --text-primary-color: #ddd;
}

p {
  color: var(--text-primary-color);
}

.el-form-item {
  margin-left: auto;
  margin-right: auto;
}


</style>
